'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
  async registry() {
    let {ctx,service} = this;
    let {username,password} = ctx.request.body;
    //容错处理
    let error = this.app.validator.validate({username:'email',password:{type: 'password', required: true, allowEmpty: false,min:4,max:6}},ctx.request.body)
    console.log("error====",error)
    if(error){
        //有错误
        ctx.body = {
            code:2,
            msg:error[0].message
        }
    }else{
        let newPwd = ctx.helper.hmac(password);
        try{
            await service.user.registry(username,newPwd);
            ctx.body = {
                code:1,
                msg:'注册成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
        
    }
  }

  async login(){
    let {ctx,service} = this;
    let {username,password} = ctx.request.body;
    //容错处理
    let error = this.app.validator.validate({username:'email',password:{type: 'password', required: true, allowEmpty: false,min:4,max:6}},ctx.request.body)
    if(error){
        //有错误
        ctx.body = {
            code:2,
            msg:error[0].message
        }
    }else{
        let newPwd = ctx.helper.hmac(password);
        let data = await service.user.login(username,newPwd);
        console.log("data",data)
        if(data.length){
            let token = jwt.sign({username,roleid:data[0].roleid},'1705d',{expiresIn:60*60})
            //登录成功
            ctx.body = {
                code:1,
                msg:'登录成功',
                token
            }
        }else{
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }
  }
}

module.exports = UserController;
